curl_escape
使用 URL 编码给定的字符串
PHP 5.5.0 及以上版本
curl_escape() 函数用于对字符串进行 URL 编码,使其能够安全地用作 HTTP 请求的一部分。这个函数主要用于将字符串中不安全的字符(如空格、特殊字符等)转义成合法的 URL 编码格式。
string curl_escape ( resource $ch , string $str )
返回一个 URL 编码后的字符串。如果函数调用失败,则返回 FALSE。
以下示例展示了如何使用 curl_escape() 函数对字符串进行 URL 编码:
<?php // 初始化 cURL 会话 $ch = curl_init(); // 需要进行编码的字符串 $str = "This is a test string with special characters: # & ? /"; // 使用 curl_escape() 进行 URL 编码 $encoded_str = curl_escape($ch, $str); // 输出编码后的字符串 echo $encoded_str; // 关闭 cURL 会话 curl_close($ch); ?>
首先,我们通过 curl_init() 函数初始化一个 cURL 会话,然后定义一个包含特殊字符的字符串 $str。接着,使用 curl_escape() 函数对该字符串进行 URL 编码,并将结果存储在 $encoded_str 中。最后,我们输出编码后的字符串,并关闭 cURL 会话。